from rest_framework import serializers
from django.contrib.auth.models import User
from .models import Cluster, Node, Instance, ResourceUsage

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'email', 'first_name', 'last_name']
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        user = User.objects.create_user(
            username=validated_data['username'],
            email=validated_data.get('email', ''),
            password=validated_data['password'],
            first_name=validated_data.get('first_name', ''),
            last_name=validated_data.get('last_name', '')
        )
        return user

class ClusterSerializer(serializers.ModelSerializer):
    class Meta:
        model = Cluster
        fields = ['id', 'name', 'description', 'created_by', 'created_at']
        read_only_fields = ['created_by', 'created_at']

class NodeSerializer(serializers.ModelSerializer):
    cluster_name = serializers.CharField(source='cluster.name', read_only=True)
    
    class Meta:
        model = Node
        fields = ['id', 'name', 'cluster', 'cluster_name', 'ip_address', 'status',
                 'cpu_cores', 'memory_gb', 'disk_gb', 'created_by', 'created_at']
        read_only_fields = ['created_by', 'created_at']

class InstanceSerializer(serializers.ModelSerializer):
    node_name = serializers.CharField(source='node.name', read_only=True)
    
    class Meta:
        model = Instance
        fields = ['id', 'name', 'node', 'node_name', 'status', 'cpu_cores',
                 'memory_gb', 'disk_gb', 'created_by', 'created_at']
        read_only_fields = ['created_by', 'created_at']

class ResourceUsageSerializer(serializers.ModelSerializer):
    class Meta:
        model = ResourceUsage
        fields = ['id', 'node', 'instance', 'cpu_usage', 'memory_usage',
                 'disk_usage', 'timestamp']
        read_only_fields = ['timestamp'] 